package cn.mfeg.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExportExcelUtil {
 
	public static void exportExcel(HttpServletRequest req,HttpServletResponse resp,HSSFWorkbook book) {
		try {
			String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ ".xls";
			String path=req.getServletContext().getRealPath("/downloadFiles");
			//生成文件 
			book.write(new FileOutputStream(new File(path,fileName)));
			//下载
			File file = new File(path+File.separator+fileName);
			InputStream fis = new BufferedInputStream(new FileInputStream(file));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			resp.reset();
			resp.addHeader("content-Disposition", "attachment;filename=" + toUtf8String(fileName));
			resp.addHeader("Content-Length", "" + file.length());
			OutputStream os = new BufferedOutputStream(resp.getOutputStream());
			resp.setContentType("application/octet-strean");
			os.write(buffer);
			os.flush();
			os.close();
			//删除
			file.delete();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 字符转换
	 * @param s
	 * @return
	 */
	public static String toUtf8String(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= '\377') {
				sb.append(c);
			} else {
				byte b[];
				try {
					b = Character.toString(c).getBytes("utf-8");
				} catch (Exception ex) {
					System.out.println(ex);
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0)
						k += 256;
					sb.append((new StringBuilder("%")).append(
							Integer.toHexString(k).toUpperCase()).toString());
				}

			}
		}
		return sb.toString();
	}
}
